use crate::{
    config::db_conn::get_db, entity::long_term_goals::Column, util::time_util::get_today_timestamp,
};
use sea_orm::ActiveValue::Set;
use sea_orm::{ColumnTrait, Condition, EntityTrait, QueryFilter};
use serde::{Deserialize, Serialize};
use tauri::command;
use uuid::Uuid;

#[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct TodoDto {
    pub no: Option<String>,
    pub name: String,
    pub desc: String,
}

#[command]
pub(crate) async fn add_todo(info: TodoDto) {
    use crate::entity::to_do_list::{ActiveModel, Column, Entity};

    let uuid = Uuid::new_v4().to_string();

    let model = ActiveModel {
        id: Default::default(),
        no: Set(uuid),
        name: Set(info.name),
        desc: Set(info.desc),
    };

    Entity::insert(model)
        .exec(get_db().expect("get the db connection failed"))
        .await
        .unwrap();
}

#[command]
pub(crate) async fn query_todo() -> Vec<TodoDto> {
    use crate::entity::to_do_list::Entity;

    let condi = Condition::all();

    let vec = Entity::find()
        .filter(condi)
        .all(get_db().expect("get the db connection failed"))
        .await
        .unwrap_or_else(|e| {
            tracing::error!("{:?}", e);
            // return empty vec
            Vec::new()
        });

    let mut todo_list = Vec::<TodoDto>::new();
    for x in vec {
        let x1 = TodoDto {
            no: Some(x.no),
            name: x.name,
            desc: x.desc,
        };
        todo_list.push(x1);
    }

    todo_list
}

#[command]
pub(crate) async fn add_to_task(todo: TodoDto) {
    use crate::entity::to_do_list::Entity;

    let condi = Condition::all().add(Column::No.eq(todo.no));

    let vec = Entity::find()
        .filter(condi.clone())
        .one(get_db().expect("get the db connection failed"))
        .await
        .unwrap_or_else(|e| {
            tracing::error!("{:?}", e);
            None
        });

    if vec.is_some() {
        let task = vec.unwrap();
        use crate::entity::task_info::ActiveModel;
        use crate::entity::task_info::Entity;

        let uuid = Uuid::new_v4().to_string();

        let ts = get_today_timestamp();

        let model = ActiveModel {
            id: Default::default(),
            no: Set(uuid),
            name: Set(task.name),
            desc: Set(task.desc),
            r#type: Set("common".to_owned()),
            status: Set("0".to_owned()),
            hard: Set("1".to_owned()),
            level: Set("1".to_owned()),
            start_time: Set(ts),
            cash_tomato: Default::default(),
        };

        Entity::insert(model)
            .exec(get_db().expect("get the db connection failed"))
            .await
            .unwrap();
    }

    Entity::delete_many()
        .filter(condi)
        .exec(get_db().expect("get the db connection failed"))
        .await
        .unwrap();
}
